package com.xyzwps.orm.mybatis.repository;

import com.xyzwps.orm.exception.TagDuplicateException;
import com.xyzwps.orm.model.Tag;
import com.xyzwps.orm.mybatis.mapper.TagMapper;
import com.xyzwps.orm.repository.TagRepository;
import com.xyzwps.orm.util.ExceptionUtils;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class MybatisTagRepository implements TagRepository {

    private final TagMapper tagMapper;

    public MybatisTagRepository(TagMapper tagMapper) {
        this.tagMapper = Objects.requireNonNull(tagMapper);
    }

    @Override
    public int insert(Tag tag) {
        try {
            tagMapper.insert(tag);
            return tag.getTagId();
        } catch (Exception ex) {
            if (ExceptionUtils.causedBy(ex, SQLIntegrityConstraintViolationException.class)) {
                throw new TagDuplicateException(tag.getTagName());
            } else {
                throw new IllegalStateException(ex);
            }
        }
    }

    @Override
    public void update(Tag tag) {
        try {
            tagMapper.update(tag);
        } catch (Exception ex) {
            if (ExceptionUtils.causedBy(ex, SQLIntegrityConstraintViolationException.class)) {
                throw new TagDuplicateException(tag.getTagName());
            } else {
                throw new IllegalStateException(ex);
            }
        }
    }

    @Override
    public void delete(int tagId) {
        tagMapper.delete(tagId);
    }

    @Override
    public Optional<Tag> selectByTagId(int tagId) {
        return Optional.ofNullable(tagMapper.selectByTagId(tagId));
    }

    @Override
    public List<Tag> selectAllForUser(int userId) {
        return tagMapper.selectByUserId(userId);
    }
}
